<script setup lang="ts">
import { ElForm, ElFormItem, ElInput, ElCheckbox, ElMessage, ElMessageBox, ElButton, ElTable, ElTableColumn, ElTag, ElPagination, ElCol } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref } from 'vue'
import { queryRoleApi, deleteRoleApi, sortRoleApi } from '@/api/role'
import type { DeleteRoleParamsType, QueryRoleParamsType, QueryRoleType, RoleType, SortRoleParamsType } from '@/api/role/types'
import { formatToDateTime } from '@/utils/dateUtil'
import { useUserStore } from '@/store/modules/user'
import { Edit, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import type { TableInstance } from 'element-plus'
import Sortable from 'sortablejs'
import { removeObjEmpty } from '@/utils/systemUtils'

const { push } = useRouter()

const { t } = useI18n()

const loading = ref<boolean>(false)

const userStore = useUserStore()

const queryRoleData = ref<QueryRoleType | undefined>(undefined)

const searchForm = ref<QueryRoleParamsType>({})

const currentPage = ref(0)

const pageSize = 25

const total = ref(0)

const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<Array<RoleType>>([])

const initSortable = () => {
  Sortable.create(multipleTableRef.value!.$el.querySelectorAll('tbody')[0], {
    onEnd: (evt) => {
      const arr = queryRoleData.value!.list!
      const page = arr[evt.oldIndex!]
      arr?.splice(evt.oldIndex!, 1)
      arr?.splice(evt.newIndex!, 0, page)
      requestSortRoleApi()
    },
    handle: 'td.el-table_1_column_1'
  })
}

const requestQueryRoleApi = async () => {
  searchForm.value.pageNum = currentPage.value
  searchForm.value.pageSize = pageSize
  let params: QueryRoleParamsType = searchForm.value
  params = removeObjEmpty(params)
  loading.value = true
  const res = await queryRoleApi(params)
  loading.value = false

  if (res.code == 1) {
    queryRoleData.value = res.data
    // roleListData.value = res.data.list
    total.value = res.data.totalSize ? res.data.totalSize : 0
    // currentPage.value += 1
    initSortable()
  }
}

const requestDeleteRoleApi = async () => {
  const ids: Array<number> = []
  multipleSelection.value.forEach((e) => {
    ids.push(e.id!)
  })
  const params: DeleteRoleParamsType = {
    ids: ids
  }
  loading.value = true
  const res = await deleteRoleApi(params)
  loading.value = false

  if (res.code == 1) {
    requestQueryRoleApi()
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
  }
}

const requestSortRoleApi = async () => {
  const params: Array<SortRoleParamsType> = []

  queryRoleData.value?.list?.forEach((e, i) => {
    params.push({
      sort: i,
      id: e.id!
    })
  })
  loading.value = true
  const res = await sortRoleApi(params)
  loading.value = false
  if (res.code == 1) {
    ElMessage({
      type: 'success',
      message: '排序成功'
    })
  }
}

requestQueryRoleApi()

const onSelectionChange = (data: Array<RoleType>) => {
  multipleSelection.value = data
}

const onSearch = () => {
  requestQueryRoleApi()
}

const onAdd = () => {
  push('/role/addRole')
}

const onModify = (id: number) => {
  push('/role/addRole?id=' + id)
}

const onDel = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage({
      type: 'warning',
      message: '请选择您要删除的数据'
    })
    return
  }
  ElMessageBox.confirm('确定要删除？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    requestDeleteRoleApi()
  })
}

const onItemDel = (item: RoleType) => {
  multipleSelection.value = []
  multipleSelection.value.push(item)
  ElMessageBox.confirm('确定要删除？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    requestDeleteRoleApi()
  })
}

const onCurrentChange = (pageNum: number) => {
  currentPage.value = pageNum
  requestQueryRoleApi()
}
</script>

<template>
  <ContentWrap title="路由查询" message="默认无条件查询" :loading="loading">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="组件名字">
        <el-input v-model="searchForm.name" placeholder="请输入组件名字" clearable />
      </el-form-item>
      <el-form-item><el-checkbox v-model="searchForm.isDel" label="是否删除" size="large" /></el-form-item>
      <el-form-item><el-checkbox v-model="searchForm.isLogin" label="是否需要登录" size="large" /></el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="primary" @click="onAdd">添加</el-button>
        <el-button type="danger" @click="onDel">删除</el-button>
      </el-form-item>
    </el-form>

    <el-table ref="multipleTableRef" row-key="id" :data="queryRoleData?.list" style="width: 100%; height: 100%" :border="true" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column property="name" label="组件名字" />
      <el-table-column property="path" label="路径" />
      <el-table-column property="component" label="组件路径" />
      <el-table-column property="redirect" label="重定向路径" />
      <el-table-column label="是否登录">
        <template #default="scope">
          <el-tag type="warning" v-if="scope.row.isLogin">需登录</el-tag>
          <el-tag type="success" v-else>无需登录</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template #default="scope">{{ formatToDateTime(scope.row.createtime * 1000, 'YYYY-MM-DD HH:ss') }}</template>
      </el-table-column>

      <el-table-column label="是否删除">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.isDel">已删除</el-tag>
          <el-tag type="success" v-else>正常</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" circle @click="onModify(scope.row.id)" />
          <el-button type="danger" :icon="Delete" circle @click="onItemDel(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex; justify-content: center; align-items: center; padding: 20px">
      <!-- total, prev, pager, next ,jumper -->
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" layout="total" :total="total" @current-change="onCurrentChange" />
    </div>
  </ContentWrap>
</template>
